# -*- coding: utf-8 -*-
import os
import tkinter as tk
import tkinter.messagebox
from tkinter import filedialog
from runtimeError import runtimeError
from analyseHtml import analyse_html
from generateExcel import generate_excel_by_data
from logger import Logger

log = Logger("App.py").logger

window = tk.Tk()
width = 400
height = 150
screenwidth = window.winfo_screenwidth()
screenheight = window.winfo_screenheight()
theEntry = tk.Entry(window, bd=3, width=37)
tableNameEntry = tk.Entry(window, bd=3, width=37)
alignstr = '%dx%d+%d+%d' % (width, height, (screenwidth - width) / 2, (screenheight - height) / 2)
sub_alignstr = '%dx%d+%d+%d' % (240, 200, (screenwidth - 200) / 2, (screenheight - 200) / 2)
showpath = ""


def button1Action():
    file_path = list(filedialog.askopenfilenames(title="选择html文件", filetypes=[('html文件', '*.html')],
                                                 initialdir=os.getcwd()))
    theEntry.configure(state="normal")
    if theEntry.get() != "":
        theEntry.delete(0, len(theEntry.get()))
    showpath = file_path[0]
    theEntry.insert(index=0, string=showpath)
    theEntry.configure(state="disabled")


def button2Action():
    try:
        theButton1.configure(state='disabled')
        theButton2.configure(state='disabled')
        htmlPath = theEntry.get()
        tableName = tableNameEntry.get()
        log.info("开始运行，解析：" + htmlPath)
        tHead, tData = analyse_html(htmlPath)
        log.info("解析成功！")
        log.info("正在导出Excel...")
        generate_excel_by_data(table_head=tHead, table_data=tData, table_name=tableName)
        log.info("导出Excel(" + tableName + ".xlsx)成功！")
        tk.messagebox.showinfo(title='运行成功', message="导出Excel(" + tableName + ".xlsx)成功！")
        theButton1.configure(state='normal')
        theButton2.configure(state='normal')
    except runtimeError as e:
        log.error(e)
        tk.messagebox.showerror(title='运行错误', message=e.str_explanation)
        theButton1.configure(state='normal')
        theButton2.configure(state='normal')


if __name__ == "__main__":
    window.title("parseHtml2excel")
    # geometry参数含义 :height*width+x+y
    window.geometry(alignstr)
    # window不可改变大小
    window.resizable(width=False, height=False)
    global theButton1, theButton2
    theButton1 = tk.Button(window, text="选择解析的html", bd=3, width=14, command=button1Action)
    theButton2 = tk.Button(window, text="开始", bd=3, width=8, command=button2Action)
    inputTip = tk.Label(window, text="输入导出表名称：", bd=3)
    theEntry.place(x=15, y=40)
    inputTip.place(x=15, y=80)
    tableNameEntry.place(x=120, y=80)
    theButton1.place(x=285, y=36)
    theButton2.place(x=160, y=110)
    window.mainloop()
